package com.jhc.common.core.web.page;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhc.common.core.annotation.Page;
import com.jhc.common.core.utils.Null;
import com.jhc.common.core.utils.PageUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;


public class PageInterceptor implements HandlerInterceptor {
    private final ObjectMapper objectMapper;

    public PageInterceptor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Page annotation = handlerMethod.getMethodAnnotation(Page.class);
            if (annotation != null) {
                // 读取请求体
                StringBuilder sb = new StringBuilder();
                try (BufferedReader reader = request.getReader()) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                }

                // 将请求体转换为PageDomain对象
                String body = sb.toString();
                if (Null.isNotEmpty(body)){
                    PageDomain pageDomain = objectMapper.readValue(body, PageDomain.class);
                    if (pageDomain.validPageParam()){
                        // 开启分页
                        PageUtils.startPage(pageDomain);
                    }
                }
            }
        }
        return true;
    }

}
